package com.paylibrary.weichat;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.paylibrary.Pay;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

public class WeiChatPay implements Pay {

    private Context context;

    private IWXAPI api;

    public WeiChatPay(Context context) {
        this.context = context;
        api = WXAPIFactory.createWXAPI(context, Constants.APP_ID);
    }


    public void weiChatPay(View payBtn, String content) {
        //检测是否安装微信
        if (!api.isWXAppInstalled()) {
            Toast.makeText(context, "请先下载微信", Toast.LENGTH_LONG).show();
            return;
        }
        Log.e("get server pay params:", content);
        try {
            JSONObject json = new JSONObject(content);
            if (null != json && !json.has("retcode")) {
                PayReq req = new PayReq();


                req.appId = json.getString("appid");
                req.partnerId = json.getString("partnerid");
                req.prepayId = json.getString("prepayid");
                req.nonceStr = json.getString("noncestr");
                req.timeStamp = json.getString("timestamp");
                req.packageValue = json.getString("packages");
                req.sign = json.getString("sign");
                req.extData = "app data"; // optional
                api.sendReq(req);
            } else {
                Log.d("PAY_GET", "���ش���" + json.getString("retmsg"));
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

//        payBtn.setEnabled(true);
    }

    @Override
    public void Pay(View v, String orderInfo) {
        weiChatPay(v, orderInfo);
    }
}
